package com.kedacom.general.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kedacom.general.param.RequestParam;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

public class RequestBodyUtil {
    // 获取请求参数体
    public static RequestParam getRequestParam(HttpServletRequest request) throws IOException {
        RequestParam requestParam = new RequestParam();
        requestParam.setMethod(request.getMethod());
        requestParam.setUrl(request.getRequestURI());
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name	= enumeration.nextElement();
            String value = request.getHeader(name);
            headerMap.put(name, value);
        }
        requestParam.setHeaderMap(headerMap);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        String str, wholeStr = "";
        if (StringUtils.isNotBlank(request.getContentType()) && request.getContentType().contains("multipart/form-data")){
            Map<String, String> stringStringMap = FileUtils.multipartFileToBase64(request);
            if (stringStringMap != null && stringStringMap.size() > 0){
                for (Map.Entry<String, String> entry : stringStringMap.entrySet()) {
                    jsonObject.put(entry.getKey(), entry.getValue());
                }
            }
            requestParam.setParam(jsonObject);
        }
        try {
            if (StringUtils.isEmpty(request.getContentType()) || !request.getContentType().contains("multipart/form-data")) {
                BufferedReader br = request.getReader();

                while ((str = br.readLine()) != null) {
                    wholeStr += str;
                }
                if (!StringUtils.isEmpty(wholeStr)) {
                    wholeStr=wholeStr.trim();
                    //判断参数方式是json还是url方式
                    if(wholeStr.startsWith("{"))
                    {
                        jsonObject= JSON.parseObject(wholeStr);
                    }else if(wholeStr.startsWith("[")){
                        jsonArray=JSON.parseArray(wholeStr);
                    }
                    else {
                        for (String str1 : wholeStr.split("&")) {
                            jsonObject.put(str1.split("=")[0], str1.split("=")[1]);
                        }
                    }
                }
            }
        } catch (Exception e) {
            //使用json方式解析

        }
        Enumeration names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = request.getParameter(name);
            jsonObject.put(name, value);
        }
        List<String> keys=new ArrayList<>();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            Object value = entry.getValue();
            if (isEmpty(value)){
                keys.add(entry.getKey());
            }
        }
        for (String key : keys) {
            jsonObject.remove(key);
        }
        requestParam.setParam(jsonObject);
        requestParam.setParam1(jsonArray);
        return requestParam;
    }
    private static boolean isEmpty(Object obj){
        //Object类型判空是和null进行对比
        if (obj == null){
            return true;
        }
        //  instanceof  判断对象所属的类型
        if ((obj instanceof List)){
            //判断list是都为空是从 list集合的长度来判断的
            return ((List) obj).size() == 0;
        }
        if ((obj instanceof String)){
            //判断Stirng类型的对象是否为空，一个是和null对比，一个是点equal("")
            return ((String) obj).trim().equals("");
        }
        return false;
    }
}
